package com.bjy.qa.agent.mock;

import com.alibaba.fastjson.JSON;
import com.bjy.qa.agent.mock.forward.ForwardService;
import com.bjy.qa.agent.mock.http.BufferedHttpServletRequestWrapper;
import com.bjy.qa.agent.mock.http.MockRequest;
import com.bjy.qa.agent.mock.http.MockResponse;
import com.bjy.qa.agent.tools.http.Params;
import com.bjy.qa.agent.tools.json.JsonHelper;
import com.bjy.qa.agent.transport.http.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/mock")
public class MockController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${qap.mock.debug:false}")
    private Boolean debug;

    @Resource
    private ForwardService forwardService;

    /**
     * mock 主入口
     * @param request 请求
     * @param response 响应
     * @return 响应
     */
    @RequestMapping(value = "**")
    public ResponseEntity<byte[]> mockMain(HttpServletRequest request, HttpServletResponse response) {
        BufferedHttpServletRequestWrapper bufferedServletRequestWrapper = new BufferedHttpServletRequestWrapper(request);

        MockRequest mockRequest = new MockRequest(bufferedServletRequestWrapper);
        if (debug) {
            logger.info("mock 请求 {}", mockRequest);
        }

        // 向服务器查询 mock 请求的响应信息
        Params body = new Params();
        body.add("mockRequest", mockRequest);
        JsonHelper jsonHelper = HttpClient.post("/mock/getMockResponse", body);
        MockResponse mockResponse = JSON.parseObject(JSON.toJSONString(jsonHelper.getObjetct("$.data")), MockResponse.class);
        if (debug) {
            logger.info("mock 返回 {}", mockResponse);
        }

        if (mockResponse.getMockForward() != null && mockResponse.getMockForward().isEnable()) { // 需要转发，则进行转发
            return forwardService.goForward(bufferedServletRequestWrapper, mockResponse.getMockForward());
        } else { // 不需要转发，直接返回 mock 信息
            // 根据查询到的响应信息，设置响应头
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.set("Content-Type", mockResponse.getContentType().getName());

            for (Map.Entry<String, String> entity : mockResponse.getHeaders().entrySet()) {
                responseHeaders.set(entity.getKey(), entity.getValue());
            }

            // 根据查询到的响应信息，设置响应 cookie
            for (Map.Entry<String, String> entity : mockResponse.getHeaders().entrySet()) {
                Cookie cookie = new Cookie(entity.getKey(), entity.getValue());
                cookie.setPath("/");
                response.addCookie(cookie);
            }

            // 根据查询到的响应信息，设置响应 状态码、body
            return ResponseEntity
                    .status(mockResponse.getStatus())
                    .headers(responseHeaders)
                    .body(mockResponse.getBody().getBytes());
        }
    }
}
